package jvs.vfs.tools;

import java.util.Arrays;
import java.util.Date;

import javax.swing.UIManager;
import javax.swing.table.AbstractTableModel;

import x.java.io.File;
import x.javax.swing.filechooser.FileSystemView;
/**
 * 
 * @author Eric Armstrong, Tom Santos, and Steve Wilson
 *
 */
public class DirectoryModel extends AbstractTableModel {
	private static final long serialVersionUID = 6401342491226236570L;

	protected File directory;

	protected String[] children;

	protected int rowCount;

	protected Object dirIcon;

	protected Object fileIcon;

	public DirectoryModel() {
		init();
	}

	private String[] list(File dir) {
		File[] files = (File[])dir.listFiles();
		if (files == null) {
			files = new File[0];
		} else {
			Arrays.sort(files);
		}
		String[] ls = new String[files.length];
		for (int i=0; i<files.length;i++) {
			ls[i] = files[i].getName();
		}
		return ls;
	}
	
	public DirectoryModel(File dir) {
		init();
		directory = dir;
		children = list(dir);
		rowCount = children.length;
	}

	protected void init() {
		dirIcon = UIManager.get("FileView.directoryIcon");
		fileIcon = UIManager.get("FileView.fileIcon");
	}

	public void setDirectory(File dir) {
		if (dir != null) {
			directory = dir;
			children = list(dir);
			rowCount = children.length;
		} else {
			directory = null;
			children = null;
			rowCount = 0;
		}
		fireTableDataChanged();
	}

	public int getRowCount() {
		return children != null ? rowCount : 0;
	}

	public int getColumnCount() {
		return children != null ? 4 : 0;
	}

	public Object getValueAt(int row, int column) {
		if (directory == null || children == null) {
			return null;
		}

		File fileSysEntity = new File(directory, children[row]);

		switch (column) {
		case 0:
			//return fileSysEntity.isDirectory() ? dirIcon : fileIcon;
			return FileSystemView.getIcon(fileSysEntity);
		case 1:
			return fileSysEntity.getName();
		case 2:
			if (fileSysEntity.isDirectory()) {
				return "";
			} else {
				return new Long(fileSysEntity.length());
			}
		case 3:
			return new Date(fileSysEntity.lastModified());
		default:
			return "";
		}
	}

	public String getColumnName(int column) {
		switch (column) {
		case 0:
			return "Type";
		case 1:
			return "Name";
		case 2:
			return "Bytes";
		case 3:
			return "Date Modified";
		default:
			return "";
		}
	}

	public Class<?> getColumnClass(int column) {
		if (column == 0) {
			return getValueAt(0, column).getClass();
		} else {
			return super.getColumnClass(column);
		}
	}
}
